
package com.pp.admin.common.server.service;

import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.pp.admin.common.client.beans.PageInfo;
import com.pp.admin.common.client.exceptions.InvalidDomain;
import com.pp.admin.common.server.CurrentThread;
import com.pp.admin.common.server.PersistenceManagerFactory;
import com.pp.admin.common.server.entities.Domain;
import com.pp.admin.common.server.entities.User;

public class BaseAdminService extends RemoteServiceServlet {
	
	/**
	 * 
	 */
	private static final long		serialVersionUID		= -4913689212711762635L;
	
	@SuppressWarnings( "unused" )
	private static final Logger		LOG						= Logger.getLogger( BaseAdminService.class.getName() );
	
	public static final String		FLD_DOMAIN_DOMAIN_ID	= "domainID";
	
	public static final String		FLD_USR_DOMN_USER_KEY	= "userKey";
	
	public static final String		FLD_USR_DOMN_DOMAIN		= "domain";
	
	public static final String		QUERY_PARAM				= "param";
	
	public static final String		RSC_SETTINGS			= "adminSettings";
	
	public static final String		CURRENT_USER			= "currentuser";
	
	public static final String		RSC_KEY_PAGE_SIZE		= "records.per.page";
	
	public static final int			DEFAULT_PAGE_SIZE		= 15;
	
	private static ResourceBundle	settings				= null;
	
	public static final String		USERID_COOKIE			= "UID";
	
	protected HttpSession getSession( boolean arg ) {

		return this.getThreadLocalRequest().getSession( arg );
	}
	
	protected void setupRequest() {

		PersistenceManager pm = PersistenceManagerFactory.getPersistenceManager();
		try {
			String userID = getCookie( USERID_COOKIE ).getValue();
			if ( userID != null && "".equals( userID ) ) {
				Key userkey = KeyFactory.createKey( User.class.getSimpleName(), userID );
				User user = pm.getObjectById( User.class, userkey );
				CurrentThread.setCurrentUser( user );
			}
		} finally {
			PersistenceManagerFactory.closePersistenceManager();
		}
	}
	
	protected Query setupPageInfo( Query query, PageInfo pageInfo, Object... args ) {

		int maxSize = ( (List) query.executeWithArray( args ) ).size();
		
		String pageSizeStr = getSetting( RSC_KEY_PAGE_SIZE );
		int pageSize = DEFAULT_PAGE_SIZE;
		if ( pageSizeStr != null ) {
			pageSize = Integer.parseInt( pageSizeStr );
		}
		pageInfo.setPageSize( pageSize );
		int noOfPages = maxSize / pageSize;
		if ( maxSize % pageSize != 0 ) {
			noOfPages++;
		}
		pageInfo.setNoOfPages( noOfPages );
		if ( pageInfo.getCurrentAction() == PageInfo.FIRST ) {
			pageInfo.setFirstPage();
		} else if ( ( pageInfo.getCurrentAction() == PageInfo.NEXT ) && ( pageInfo.getCurrentPage() < noOfPages ) ) {
			pageInfo.setNextPage();
		} else if ( ( pageInfo.getCurrentAction() == PageInfo.PREV ) && ( pageInfo.getCurrentPage() > 1 ) ) {
			pageInfo.setPrevPage();
		} else if ( pageInfo.getCurrentAction() == PageInfo.LAST ) {
			pageInfo.setLastPage( noOfPages );
		}
		
		int toRange = pageInfo.getCurrentPage() * pageInfo.getPageSize();
		query.setRange(toRange - pageInfo.getPageSize(), toRange);

		
		return query;
	}
	
	protected Cookie getCookie( String name ) {

		Cookie resp = null;
		Cookie[] cookies = this.getThreadLocalRequest().getCookies();
		for ( int index = 0; index < cookies.length; index++ ) {
			if ( cookies[index].getName().equals( name ) ) {
				resp = cookies[index];
			}
		}
		return resp;
	}
	
	public static String getSetting( String key ) {

		if ( settings == null ) {
			settings = ResourceBundle.getBundle( RSC_SETTINGS );
		}
		return settings.getString( key );
	}
	
	public Domain getDomainEntityByDomainID( String domainID ) throws InvalidDomain {

		Domain resp = null;
		PersistenceManager pm = PersistenceManagerFactory.getPersistenceManager();
		try {
			Query query = pm.newQuery( Domain.class, FLD_DOMAIN_DOMAIN_ID + " == '" + domainID + "'" );
			List<Domain> domainresults = (List<Domain>) query.execute();
			for ( Domain domain : domainresults ) {
				if ( domain.getDomainID().equals( domainID ) ) {
					resp = domain;
				}
			}
			if ( resp == null ) {
				throw new InvalidDomain();
			}
		} catch ( InvalidDomain ex ) {
			throw ex;
		} catch ( Exception ex ) {
			throw new InvalidDomain();
		} finally {
			PersistenceManagerFactory.closePersistenceManager();
		}
		return resp;
	}
}
